package cn.layku.web.config;

import cn.layku.web.util.ApiResult;
import com.google.common.cache.Cache;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

@Aspect
@Component
public class NoRepeatSubmitAop {
    @Resource
    private Cache<String, Integer> cache;

    @Around("execution(* cn.layku.web.controller.*Controller.*(..)) && @annotation(nrs)")
    public Object around(ProceedingJoinPoint pjp, NoRepeatSubmit nrs) {
        try {
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            String sessionId = Objects.requireNonNull(RequestContextHolder.getRequestAttributes()).getSessionId();
            HttpServletRequest request;
            if (attributes != null) {
                request = attributes.getRequest();
                String key = sessionId + "-" + request.getServletPath();
                System.out.println("key:" + key);
                // 如果缓存中有这个url视为重复提交
                if (cache.getIfPresent(key) == null) {
                    Object o = pjp.proceed();
                    cache.put(key, 0);
                    return o;
                } else {
                    System.out.println("重复提交");
                    return ApiResult.failResult("抱歉，不允许重复提交数据！");
                }
            }
        } catch (Throwable e) {
            e.printStackTrace();
            System.out.println("验证重复提交时出现未知异常!");
            return ApiResult.failResult("抱歉，验证重复提交时出现未知异常！");
        }
        return null;
    }

}
